/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.ventas;

import dp1.titandevelop.titano.bean.FiltroDemanda;
import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.Demanda;
import dp1.titandevelop.titano.persistent.DetalleDamanda;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.service.DemandaService;
import dp1.titandevelop.titano.service.ValidacionService;
import dp1.titandevelop.titano.view.MensajeError;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.access.DataContext;

/**
 *
 * @author heli
 */
public class ModulosT_VEN_PProduccionNuevo extends javax.swing.JInternalFrame {
public Integer tipo;
public FiltroDemanda busqueda; 
public Integer iddemanda;
public Date bfin,bini;
public String bdescripcion;
public Integer bestado;
private Mensajes sms = new Mensajes();
    /**
     * Creates new form ModulosT_ALM_TMovNuevo
     */
    private List <DetalleDamanda> dDm=new ArrayList<DetalleDamanda>();
    
        public void habilitaBotones(){
            this.btnEliminarA.setEnabled(true);
        
         }
    private void inhabilitaBotones(){
        this.btnEliminarA.setEnabled(false);
        
    }
    
    private void inhabilitarTodo(){
          this.btnEliminarA.setVisible(false);
          this.btnNuevo.setVisible(false);
          this.btnGuardar.setVisible(false);
          this.txtFecha.setEditable(false);
          this.txtDescripcion.setEditable(false);
          this.txtFecha.setEditable(false);
      
    }
    
    public ModulosT_VEN_PProduccionNuevo() {
        initComponents();
       this.tipo=0; 
       ValidacionService validacionService = new ValidacionService();
        validacionService.SLetras(this.txtDescripcion);
        validacionService.NoEscribe(this.txtFecha);
        inhabilitaBotones();
       
    }
    
    public ModulosT_VEN_PProduccionNuevo(Demanda d,FiltroDemanda busqueda, Integer tipo) {
        initComponents();
        this.setTitle("Ventas - Editar Demanda");
        ValidacionService validacionService = new ValidacionService();
        validacionService.SAlfanumerico(this.txtDescripcion);
        validacionService.NoEscribe(this.txtFecha);
        
        validacionService.Longitud(this.txtDescripcion,50);
        
        DemandaService service=new DemandaService();
        this.txtFecha.setDate(d.getFecha());
        this.txtDescripcion.setText(d.getDescripcion());
        System.out.println("iddemanda: "+d.getIddemanda());
        this.dDm=service.buscarFiltrado2(d.getIddemanda());
        this.busqueda=busqueda;
        inhabilitaBotones();
        
        this.actualizarDemandaList();
        this.tipo=tipo;
        this.iddemanda=d.getIddemanda();
        System.out.println(this.iddemanda);
        if(this.tipo==2){
            this.setTitle("Ventas - Ver Demanda");
        this.inhabilitarTodo();
        }
    }

    private void actualizarD(){
        dDm.clear();
    DemandaService service=new DemandaService();
    this.dDm=service.buscarFiltrado2(this.iddemanda);
    
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jXDatePicker1 = new org.jdesktop.swingx.JXDatePicker();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtDescripcion = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtFecha = new org.jdesktop.swingx.JXDatePicker();
        btnGuardar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableResultados = new javax.swing.JTable();
        btnNuevo = new javax.swing.JButton();
        btnEliminarA = new javax.swing.JButton();

        setResizable(true);
        setTitle("Nueva Demanda");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos"));

        jLabel1.setText("Fecha");

        jLabel5.setText("Descripción");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel1))
                .addGap(29, 29, 29)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtDescripcion)
                        .addGap(131, 131, 131))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8))
        );

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        btnCancelar.setToolTipText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalle Demanda"));

        tableResultados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Producto", "Unidad", "Cantidad"
            }
        ));
        tableResultados.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableResultadosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tableResultados);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 422, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        btnNuevo.setToolTipText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnEliminarA.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btnEliminarA.setToolTipText("Eliminar");
        btnEliminarA.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarAActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(btnNuevo)
                        .addGap(1, 1, 1)
                        .addComponent(btnEliminarA)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, 0)
                        .addComponent(btnCancelar))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(8, 8, 8))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnGuardar)
                    .addComponent(btnCancelar)
                    .addComponent(btnNuevo)
                    .addComponent(btnEliminarA))
                .addGap(8, 8, 8))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        ModulosT_VEN.menuItemPP = new ModulosT_VEN_PProduccion(this.busqueda);
        this.getParent().add(ModulosT_VEN.menuItemPP);
        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize =  ModulosT_VEN.menuItemPP.getSize();
        ModulosT_VEN.menuItemPP.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height)/4 );
        ModulosT_VEN.menuItemPP.show();
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed
Thread actualizardemanda = null;
    private void actualizarDemandaList(){
        if( actualizardemanda!=null && actualizardemanda.isAlive() ){
            actualizardemanda.interrupt();
        }
        actualizardemanda = new Thread( new Runnable() {
            @Override
            public void run() {
                RefreshTable();
                ModeloTabla modelo= new ModeloTabla();
                tableResultados.setModel(modelo);
                
            }
        });
        actualizardemanda.start();
    }
    
    
    //metodo para refrescar la tabla
    public void RefreshTable() {
        
        AbstractTableModel aux = (AbstractTableModel)tableResultados.getModel();
        aux.fireTableDataChanged();
    }
    
    class ModeloTabla extends AbstractTableModel {  
        //Atributos de los datos de la tabla
        private String [] titles = {"Producto","Unidad", "Cantidad"};
        //private List<DataTabla> datos;
        //private Object [][]datos;
        
        public int getRowCount() {
            return dDm.size();//tipos.size(); // cuantos registros (filas)
        }      
        
        public int getColumnCount() {
            return 3; // cuantas columnas
        }          
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }                
       
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object res=null;
            DetalleDamanda d2 = dDm.get(rowIndex);
            //boolean b = datos.get(rowIndex).seleccionado;//tipos.get(rowIndex);
            switch(columnIndex){
                case 0: res = d2.getToProducto().getDescripcion(); break;
                case 1: res = d2.getToProducto().getUm(); break;
                case 2: res = d2.getCantidad(); break;
                //case 2: res = b;
            }
            return res;
        } 
        //Ultima celda editable para selección
        @Override
        public boolean isCellEditable(int row, int col) {
            boolean res=false;
            switch (col) {
                case 0:break;
                case 1:break;
               // case 2:res=true;
            }
            return res;
        }
        //para obtener las clases de cada celda y asi mostrar estas correctamente
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
//        @Override
//        public void setValueAt(Object value, int row, int col) {
//            datos.get(row).seleccionado = (Boolean)value;
//        }
    }
    
    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        Mensajes mensajes = new Mensajes();
        ValidacionService validacionService = new ValidacionService();
        if ((validacionService.esVacio(this.txtDescripcion)) || (validacionService.esFechaVacia(this.txtFecha))) {
            JOptionPane.showInternalMessageDialog(this.getRootPane(), mensajes.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);

        } else {
        try {

            //Demanda dm =null;
            ObjectContext context = DataContext.createDataContext();
            Demanda dm=(Demanda)context.newObject(Demanda.class);
            dm.setDescripcion(this.txtDescripcion.getText());
            dm.setFecha(this.txtFecha.getDate());
            dm.setIddemanda(iddemanda);
            DemandaService service=new DemandaService();
                    System.out.println(this.txtDescripcion.getText());
              if(this.tipo==0){
                service.insertar(dm, dDm);
                JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getRegistrado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);
              }
            if(this.tipo==1){
                service.editar(dm);
                JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getEditado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);
            }
            
            
            
            } catch(Exception e) {

                  MensajeError dialog = new MensajeError(new javax.swing.JFrame(), true);
                  dialog.setLocationRelativeTo(null);
                  dialog.setVisible(true);
                  System.out.println("sali x aki");
            }
        
        ModulosT_VEN.menuItemPP = new ModulosT_VEN_PProduccion();
        this.getParent().add(ModulosT_VEN.menuItemPP);
        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize =  ModulosT_VEN.menuItemPP.getSize();
        ModulosT_VEN.menuItemPP.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height)/4 );
        ModulosT_VEN.menuItemPP.show();
        
        this.dispose();
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
       final int i=0;
        final busquedaProductoCantidad2 seleccionarProductoForm =new busquedaProductoCantidad2(null, true);
        seleccionarProductoForm.setLocationRelativeTo(this);
        seleccionarProductoForm.addWindowListener(new WindowAdapter() {
                        @Override
			public void windowClosed(WindowEvent e) {
                            if(seleccionarProductoForm.idProducto!=null){
                           int cantx=0,iddetalledemandax=0,posx=-1;
                                if(seleccionarProductoForm.idProducto>0){
                                int aumentar=1;
                                
                                DetalleDamanda d=new DetalleDamanda();
                                d.setCantidad(seleccionarProductoForm.cantidad);
                                ObjectContext context = DataContext.createDataContext();
                                Producto p=(Producto)context.newObject(Producto.class);
                                p.setIdproducto(seleccionarProductoForm.idProducto);
                                p.setDescripcion(seleccionarProductoForm.producto);
                                p.setUm(seleccionarProductoForm.unidad);
                                d.setToProducto(p);
                                seleccionarProductoForm.idProducto=0;
                                
                                for(int i=0;i<dDm.size();i++){
                                    if(dDm.get(i).getToProducto().getDescripcion().equals(p.getDescripcion()) || dDm.get(i).getToProducto().getIdproducto().equals(p.getIdproducto()) ){
                                        
                                        if(tipo==1)
                                            posx=i;
                                        else
                                        dDm.get(i).setCantidad(d.getCantidad());
                                       
                                        aumentar=0;
                                        if(dDm.get(i).getIddetalledemanda()!=null){
                                        cantx=d.getCantidad();
                                        iddetalledemandax=dDm.get(i).getIddetalledemanda();
                                        }
                                    }
                                }
                                
                                
                                if(tipo==1){
                                DemandaService service= new DemandaService();
                                Demanda dd=(Demanda)context.newObject(Demanda.class);
                                System.out.println(iddemanda);
                                dd.setIddemanda(iddemanda);
                                d.setToDemanda(dd);
                            
                                if(aumentar==1){
                                    int confirmar = JOptionPane.showInternalConfirmDialog(getRootPane(),"¿Está seguro que desea aumentar el producto seleccionado a su demanda? esto se registrará de manera permanente","Aviso!",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);

                                    if (JOptionPane.OK_OPTION == confirmar){
                                        service.agregarItem(d);
                                    }else{
                                        aumentar=0;
                                    }
                                }else{
                                    if(cantx!=0 && iddetalledemandax!=0){
                                        int confirmar = JOptionPane.showInternalConfirmDialog(getRootPane(),"¿Está seguro que desea modificar la cantidad del producto seleccionado?, su cambio sera permantente","Aviso!",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);

                                       if (JOptionPane.OK_OPTION == confirmar){
                                        System.out.println("Voy a editar el iddetalledemanda="+iddetalledemandax);
                                       service.editarItem(iddetalledemandax,cantx);
                                       if(posx>-1){
                                       dDm.get(posx).setCantidad(d.getCantidad());
                                       }
                                       }else{
                                       aumentar=0;
                                       }
                                    }
                                }
                              }
                                
                                
                                if(aumentar==1) dDm.add(d);
                                
                           if(tipo==1) actualizarD();     
                           actualizarDemandaList();

                            }
                           }
                            //this;
			}
		});
        seleccionarProductoForm.setVisible(true);        
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void btnEliminarAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarAActionPerformed
        int confirmar = JOptionPane.showInternalConfirmDialog(this.getRootPane(),"¿Está seguro que desea eliminar el registro?","Aviso!",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);

        if (JOptionPane.OK_OPTION == confirmar)
        {//Obtengo el objeto seleccionado
            DemandaService serv = new DemandaService();
            DetalleDamanda dist = dDm.get(this.tableResultados.getSelectedRow());
            this.dDm.remove(this.tableResultados.getSelectedRow());
            if(this.tipo==1)
            serv.eliminarItemDetalle(dist.getIddetalledemanda());
        }

        this.RefreshTable();
        this.inhabilitaBotones();
    }//GEN-LAST:event_btnEliminarAActionPerformed

    private void tableResultadosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableResultadosMouseClicked
        this.habilitaBotones();
    }//GEN-LAST:event_tableResultadosMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEliminarA;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXDatePicker jXDatePicker1;
    private javax.swing.JTable tableResultados;
    private javax.swing.JTextField txtDescripcion;
    private org.jdesktop.swingx.JXDatePicker txtFecha;
    // End of variables declaration//GEN-END:variables
}
